/*
Rilego - An easy Images 2 E-Book converter.
Copyright (C) 2011  Federico Improta (Kirys)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package it.kirys.rilego.engine.processors;

import it.kirys.rilego.engine.Engine;
import it.kirys.rilego.engine.outputbuilders.MediaType;
import it.kirys.rilego.engine.loaders.imagesources.IImageSource;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Federico Improta
 */
public class RawCopyProcessor implements IImageProcessor {

	IImageSource source;
	ProcessorOutput[] output;
	Engine engine;

	public static synchronized void copy(InputStream from, OutputStream to) throws IOException {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(from);
			out = new BufferedOutputStream(to);
			while (true) {
				int data = in.read();
				if (data == -1) {
					break;
				}
				out.write(data);
			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}//public static void copy(InputStream from, OutputStream to) throws IOException

	@Override
	public void run() {
		InputStream ss = null;
		try {
			output = null;
			ProcessorOutput out = new ProcessorOutput();
			out.setType(source.getType());
			ss = source.getStream();
			try {
				copy(ss, out);
			} catch (IOException ex) {
			}
			output = new ProcessorOutput[]{out};
		} catch (IOException ex) {
			engine.logException("Error during image Processing", ex);
		} finally {
			try {
				ss.close();
			} catch (IOException ex) {
				engine.logException("Error during image Processing", ex);
			}
		}

	}

	@Override
	public Engine getEngine() {
		return engine;
	}

	public RawCopyProcessor(IImageSource source, Engine engine) {
		this.source = source;
		this.engine = engine;
	}

	@Override
	public IImageSource getSourceImage() {
		return source;
	}

	@Override
	public ProcessorOutput[] getOutput() {
		return output;
	}
}
